package cn.com.smart.common.utils;

import cn.com.smart.module.system.user.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JWTUtil {
    /**
     * 有效期7天
     */
    private static final int EXPIRE_TIME = 7;

    /**
     * 盐
     */
    private static final String signingKey = "ponyms";

    /**
     * 根据用户信息创建token,目前只将用户id和用户机构id放进了token，后续可自由添加
     *
     * @param user
     * @return
     */
    public static String createToken(User user) {
        //签发时间
        Date iatTime = new Date();
        //expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.DATE, EXPIRE_TIME);
        Date expireTime = nowTime.getTime();

        Claims claims = Jwts.claims();
        claims.setId(user.getLoginName());
        //将用户信息放入token
        claims.put("userId", user.getUserId());
        claims.put("orgId", user.getOrgId());
        claims.setIssuedAt(iatTime);

        String token = Jwts.builder().setClaims(claims).setExpiration(expireTime)
                .signWith(SignatureAlgorithm.HS256, signingKey).compact();
        return token;
    }

    /**
     * 解析token返回用户实体类，为null则代表token无效
     *
     * @param token
     * @return
     */
    public static User parseToken(String token) {
        Jws<Claims> jws;
        try {
            jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);
        } catch (Exception e) {
            return null;
        }

        Claims claims = jws.getBody();
        Map<String, String> header = jws.getHeader();
        User user = new User();
        user.setUserId(((Number) claims.get("userId")).longValue());
        user.setOrgId(((Number) claims.get("orgId")).longValue());
        user.setUserName(claims.getId());
        return user;
    }

}
